package com.gcxy.tour.common;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.tour.common.JdbcUtils;

/**
 * 内容：链接数据库
 * @author 方昆
 *
 */
public class JdbcUtils {

	
    //TODO 修改数据库路径和用户
	private static String username="root";
	private static String password="root";
	private static String url="jdbc:mysql://localhost/productdb?useSSL=false";
	
	private static Logger logger=LoggerFactory.getLogger(JdbcUtils.class);
	static {
		try {
			//读取配置文件
			Properties prop=new Properties();
			InputStream inputStream=JdbcUtils.class.getResourceAsStream("/jdbc.properties");
			prop.load(inputStream);
			//获取配置参数
			username=prop.getProperty("jdbc.username");
			password=prop.getProperty("jdbc.password");
			url=prop.getProperty("jdbc.url");
			
			Class.forName(prop.getProperty("jdbc.driver"));
			logger.debug("初始化mysql驱动");
		} catch (ClassNotFoundException | IOException e) {
			logger.error("初始化驱动或读取参数异常:{}",e.getMessage());
		}
	}
	/**
	 * 获取数据库链接
	 * @return
	 */
	public static Connection getConnection() {
		try {
			return DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			logger.error("获取数据库链接异常:{}",e.getMessage());
			return null;
		}
	}
	/**
	 * 关闭公共的资源
	 * @param conn
	 * @param ps
	 * @param rs
	 */
	public static void close(Connection conn,Statement ps,ResultSet rs) {
		try {
			if(rs!=null) {
				rs.close();
			}
		} catch (Exception e) {
			logger.error("关闭ResultSet资源异常:{}",e.getMessage());
		}finally {
			try {
				if(ps!=null) {
					ps.close();
				}
			} catch (Exception e2) {
				logger.error("关闭Statement资源异常:{}",e2.getMessage());
			} finally {
				try {
					if(conn!=null) {
						conn.close();
					}	
				} catch (Exception e3) {
					logger.error("关闭Connection资源异常:{}",e3.getMessage());
				}
			}
		}
	}

}
